<template>
  <el-table
    :data="tableData"
    style="width: 100%"
    :default-sort="{ prop: 'date', order: 'descending' }"
  >
    <el-table-column
      label="编号"
      sortable
      width="180"
      type="index"
      :index="indexMethod"
    >
    </el-table-column>

    <el-table-column prop="title" label="标题" width="180"> </el-table-column>

    <el-table-column prop="date" label="添加时间" width="200">
    </el-table-column>

    <el-table-column label="操作">
      <template slot-scope="scope">
        <el-button size="mini" @click="handleEdit(scope.$index, scope.row)"
          >编辑</el-button
        >
        <el-button
          size="mini"
          type="danger"
          @click="handleDelete(scope.$index, scope.row)"
          >删除</el-button
        >
      </template>
    </el-table-column>
  </el-table>
</template>

<script>
import api from "../../../api";

export default {
  name: "Table",
  data() {
    return {
      tableData: [],
    };
  },
  methods: {
    //自定义编号
    indexMethod(index) {
      return index + 1;
    },
    //编辑表格
    handleEdit(index, row) {
      this.$bus.$emit("bannerTable", row);
    },
    //删除表格
    handleDelete(index, row) {
      console.log(row);
      let id = row.id;
      let title = row.title;
      let burl = row.burl;
      let content = row.content;

      api.bannerDelete({ id, title, burl, content }).then((res) => {
        if (res.status == 200) {
          this.$message({
            message: "删除成功",
            type: "success",
          });
          //重新渲染数据
          this.http();
        } else {
          this.$message({
            message: "删除失败",
            type: "error",
          });
        }
      });
    },
    //重新渲染数据
    http() {
      api.bannerManager().then((res) => {
        if (res.status == 200) {
          let arr = res.data;

          for (let ele of arr) {
            ele.date = ele.starttime.slice(0, 10);
          }

          this.tableData = arr;
        }
      });
    },
  },
  mounted() {
    //查找数据
    this.http();

    this.$bus.$on("bannerHttp", (value) => {
      if (value) {
        this.http();
      }
    });
  },
};
</script>

<style>
</style>